<template>
  <Modal :value="modal" @on-visible-change="vchange" :title="modalTitle" width="40%" :mask-closable="modalType === 3">
		<Form :label-width="80" :model="modalData" ref="form" :rules="rules" class="jobForm">
			<Row :gutter="32">
        <Col :md="23">
          <FormItem label="岗位名称" prop="jobName">
          	<Input v-model="modalData.jobName" :maxlength="20" placeholder="请填写岗位名称" :disabled="modalType === 3"></Input>
     			</FormItem>
        </Col>
      </Row>
      <Row :gutter="32">
        <Col :md="23">
          <FormItem label="岗位描述" prop="description">
          	<Input v-model="modalData.description" :maxlength="100" placeholder="请填写岗位描述" type="textarea" :disabled="modalType === 3"></Input>
     			</FormItem>
        </Col>
      </Row>
      <Row :gutter="32">
        <Col :md="23">
          <FormItem prop="ids" class="tree-item">
            <Input v-model="modalData.ids" />
            <div class="tree-box">
              <Tree ref="tree" :data="tree" show-checkbox @on-check-change="treeChange"></Tree>
            </div>
     			</FormItem>
        </Col>
      </Row>
			<Spin size="large" fix v-if="isModalLoading"></Spin>
		</Form>
    <div slot="footer">
        <Button  @click="close">取消</Button>
        <Button type="primary" v-if="modalType !== 3" :loading="isModalLoading" @click="submit">保存</Button>
    </div>
	</Modal>
</template>

<style lang="less" scoped>
  .tree-box{
    height:250px;overflow-y:auto;line-height:1.5;
  }
  .tree-item{
    .ivu-input-wrapper{
      display: none;
    }
  }
</style>

<script>
	import {mapState,mapActions,mapMutations} from 'vuex'
  import {post} from '@/util/request'

  export default {
    props:['jobId','modal','modalTitle','modalType'],//modalType : 1：新增；2：修改；3：查看
    data(){
      return {
        modalData:{jobName:'',description:'',ids:''},
        tree:[],
        treeError: '',
        rules:{
          jobName:{required:true, message:'岗位名称必填', trigger:'blur'},
          ids:{required:true, message:'请至少选择一项权限', trigger:'change'}
        }
      }
    },
    watch:{
      jobId(v){
        if (v === null) return;
        if (v){
          this.loadView(v);
        }
        this.loadAuthList({jobId:v,type:this.modalType});
      },
      detail(v){
        this.modalData = {...this.modalData,...v};
      },
      authList(v) {
        this.tree = this.createAuthTree(0);
        let ids = v.filter(v => v.checked).map(v => v.id).join(',');
        this.modalData.ids = ids;
      }
    },
    computed:{
      ...mapState('system/job',['detail','authList','isModalLoading'])
    },
    methods:{
      ...mapActions('system/job',['loadView','loadAuthList','submitAdd','submitEdit']),
      // 无限递归创建树形权限
      createAuthTree(pid){
        let ary = [];
        this.authList.forEach((v,i) => {
          let o = {...v};
          if (o.parentid === pid) {
            o.children = this.createAuthTree(o.id);
            // 如果是父级节点，由子节点来觉得父节点的选择状态
            if (o.children.length > 0) o.checked = false;
            ary.push(o);
          }
        });
        return ary;
      },
      treeChange(nodes){
        let ary = nodes.map(v => { return [v.id,v.parentid]; });
        let lst = [];
        ary.forEach(([id,pid]) => {
          lst.push(id);
          pid && lst.push(pid);
        });
        lst = [...new Set(lst)];
        this.modalData.ids = lst.join(',');
      },
      vchange(e){
        !e && this.close();
      },
      close(){
        this.modalData = {jobName:'',description:'',ids:''};
        this.tree = [];
        this.$emit('closeDetail');
        this.$refs.form.resetFields();
      },
      submit(){
        this.$refs.form.validate(async (v)=>{
          if(v){
            let form = this.modalData;
            let res = form.id ? await this.submitEdit(form) : await this.submitAdd(form);
            if (res.success){
              this.close();
              this.$Message.success('保存成功');
              if (form.id) {
                return this.$emit('edit');
              }
              this.$emit('add');
            }else{
              this.$Message.success(res.msg);
            }
          }
        });
      }
    }
  };
</script>
